package com.situ.stmall.manger.controller.api;
import com.github.pagehelper.PageInfo;
import com.situ.stmall.manger.entity.Category;
import com.situ.stmall.manger.entity.Result;
import com.situ.stmall.manger.service.CategoryService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;

//相当于Controller与ResponseBody结合体
//将当前类放入spring的bean容器中,所有处理器方法，返回Json格式的数据
@RestController
@RequestMapping("/api/category")         //给当前的所有的处理器方法，添加URL映射的前缀
public class APICategoryController {
    @Resource
    private CategoryService categoryService;

    //添加操作
    @PostMapping
    public Result add(@RequestBody Category category) {
        try {
            int code = categoryService.add(category);
            //添加成功
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            //添加失败
            return Result.error(e.getMessage());
        }
    }

    //删除
    @DeleteMapping
    public Result remove(Integer id) {
        try {
            int code = categoryService.remove(id);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    //修改
    @PutMapping
    public Result edit(@RequestBody Category category) {
        try {
            int code = categoryService.edit(category);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    //根据条件查询
    @GetMapping
    public Result get(Integer page, Integer limit, Category category) {
        if (page == null) {//没有分页信息
            List<Category> list = categoryService.search(category);
            return Result.success(list);
        } else {
            //引入分页插件
            PageInfo pageInfo = categoryService.searchByPage(page, limit, category);
            return Result.success(pageInfo);
        }
    }

    //通过路径参数传递ID，放在URl的参数上
    @GetMapping("/{id}")
    public Result get(@PathVariable("id") Integer id) {//@PathVariable 取出路径的参数，绑定到id上
        Category category = categoryService.getById(id);
        if (category == null) {
            return Result.error("ID不存在");
        } else {
            return Result.success(category);
        }
    }
}
